<?php

namespace app\wechat\controller;

use app\common\enums\ResultEnum;
use app\common\model\Article as ArticleModel;
use app\common\utils\ResultVOUtil;
use think\Controller;
use think\Request;
use think\facade\Log;
use app\common\model\Category;

class Article extends Controller
{
    /**
     * 文章列表初始数据
     *
     * @return \think\Response
     */
    public function index()
    {
        
        $article = new ArticleModel();
        $cate = new Category();
        try {
            $data['article'] = $article->limit(10)->select();
            $data['cate'] = $cate->where('pid=0')->limit(10)->select();
        } catch (\Exception $e) {
            Log::record('[文章管理]列表:'.$e->getMessage(),'error');
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }
        return ResultVOUtil::success($data);
    }

    /**
     * 文章翻页搜索
     *
     * @return \think\Response
     */
    public function list($search='',$length=10,$page=1,$cate=0)
    {
        $where = [];
        
        if ( !empty($search) ) {
            
            $where[] = ['title','like','%'.$search.'%'];
        }
        $cateModel = new Category();
        
        if($cate){
            try {
                $cid = $cateModel->where(['pid'=>$cate])->column('id');
            } catch (\Exception $e) {
            }
            $where[] = ['cid','in',$cid];
        }

        try {
            $model = ArticleModel::where($where)
            ->paginate($length,false,[
                'type'     => 'bootstrap',
                'var_page' => 'page',
                'page'=>$page,
            ]);
            
        } catch (\Exception $e) {
            Log::record('[文章管理]列表:'.$e->getMessage(),'error');
            return ResultVOUtil::error(ResultEnum::FIND_ERROR);
        }
        return ResultVOUtil::success($model);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 文章详情
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id=1)
    {
        $model = ArticleModel::get($id);
        $model['detail'];
        if($model){
            return ResultVOUtil::success($model);
        }else{
            return ResultVOUtil::error(ResultEnum::FIND_ERROR['code'],'查询为空');
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
